package com.difsonapps.android.marker.activities;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.difsonapps.android.marker.AppConstant;
import com.difsonapps.android.marker.CustomRequest;
import com.difsonapps.android.marker.R;
import com.difsonapps.android.marker.R.layout;
import com.difsonapps.android.marker.R.menu;
import com.difsonapps.android.marker.app.AppController;
import com.difsonapps.android.marker.beans.Photo;
import com.difsonapps.android.marker.beans.User;

import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class RegisterActivity extends Activity {
	public static final String EXTRA_USER = "com.difsonapps.android.marker.extra.USER";
	public static final String EXTRA_AUTH = "com.difsonapps.android.marker.extra.AUTH";
	//View loadingLayout;
	View formScrollView;
	View codeScrollView;
	//TextView loadingStatusMessage;
	//TextView messageTextView;
	
	Button registerButton;
	
	EditText firstnameEditText;
	EditText lastnameEditText;
	EditText emailEditText;
	EditText confirmEmailEditText;
	EditText passwordEditText;
	EditText confirmPasswordEditText;
	EditText codeEditText;
	private TextView errorTextView;
	
	ProgressDialog loadingProgressDialog;
	
	//String currentUserEmail = null;
	//int currentUserId;
	
	User currentUser;
	
	private int step = 1; //1 for registration and 2 for activation
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		getActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.main_color)));

        errorTextView = (TextView) findViewById(R.id.errorTextView);
		//loadingLayout = findViewById(R.id.loading_status);
		formScrollView = findViewById(R.id.formScrollView);
		codeScrollView = findViewById(R.id.codeScrollView);
		
		//loadingStatusMessage = (TextView) findViewById(R.id.loading_status_message);
		//messageTextView = (TextView) findViewById(R.id.messageTextView);
		
		firstnameEditText = (EditText) findViewById(R.id.firstnameEditText);
		lastnameEditText = (EditText) findViewById(R.id.lastnameEditText);
		emailEditText = (EditText) findViewById(R.id.emailEditText);
		confirmEmailEditText = (EditText) findViewById(R.id.confirmEmailEditText0);
		passwordEditText = (EditText) findViewById(R.id.passwordEditText);
		confirmPasswordEditText = (EditText) findViewById(R.id.confirmPasswordEditText);
		codeEditText = (EditText) findViewById(R.id.codeEditText);
		
		registerButton = (Button)findViewById(R.id.registerButton);
		registerButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				execute();
			}
		});
		
		TextView loginScreen = (TextView) findViewById(R.id.link_to_sign_in);
		loginScreen.setOnClickListener(new View.OnClickListener() {
 
            public void onClick(View v) {
                RegisterActivity.this.finish();
            }
        });
		
		currentUser = getIntent().getParcelableExtra(EXTRA_USER);
		if(currentUser!=null){
			showValidatStep();
		}
		
		this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.register, menu);
		return true;
	}
	
	private void showProgress(){
		loadingProgressDialog = ProgressDialog.show(this, getResources().getString(R.string.loading), getResources().getString(R.string.loading), true);
        loadingProgressDialog.setCancelable(true);
		//loadingLayout.setVisibility(View.VISIBLE);
	}
	
	private void hideProgress(){
		if(loadingProgressDialog!=null) loadingProgressDialog.dismiss();
		//loadingLayout.setVisibility(View.GONE);
	}
	
	private void execute(){
		if(step==1) register();
		else validate();
	}
	
	private void register(){
		String firstname = firstnameEditText.getText().toString().trim();
		String lastname = lastnameEditText.getText().toString().trim();
		String email = emailEditText.getText().toString().trim();
		String confirmEmail = confirmEmailEditText.getText().toString().trim();
		String password = passwordEditText.getText().toString();
		String confirmPassword = confirmPasswordEditText.getText().toString();
		if(firstname.equals("")){
			toast(getResources().getString(R.string.type_firstname));
			return;
		}
		if(lastname.equals("")){
			toast(getResources().getString(R.string.type_lastname));
			return;
		}
		if(email.equals("")){
			toast(getResources().getString(R.string.type_email));
			return;
		}
		if(email.equals("")){//TODO Validate email here
			toast(getResources().getString(R.string.email_not_correct));
			return;
		}
		if(!email.equals(confirmEmail)){
			toast(getResources().getString(R.string.emails_not_match));
			return;
		}
		if(password.equals("")){
			toast(getResources().getString(R.string.type_password));
			return;
		}
		if(!password.equals(confirmPassword)){
			toast(getResources().getString(R.string.passwords_not_match));
			return;
		}
		//toast("Every things ok");
		errorTextView.setText("");
		errorTextView.setVisibility(View.GONE);
		Map<String, String> params = new HashMap<String, String>();
        params.put("firstname", firstname);//TODO Put the id of the image selected here
        params.put("lastname", lastname);
        params.put("email", email);
        params.put("password", password);
		showProgress();
		CustomRequest jsObjRequest = new CustomRequest(
				Method.POST, 
				AppConstant.registerUrl, 
				params,
				new Response.Listener<JSONObject>() {
					 
                    @Override
                    public void onResponse(JSONObject response) {
                    	hideProgress();
                    	toast("Response : "+response.toString());
                    	Log.i("Test", response.toString());
                    	parseJsonRegister(response);
                    }
                },
                new Response.ErrorListener() {
 
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    	hideProgress();
                    	toast("Error: " + error.getMessage());
                    	Log.e("Test", error.getMessage());
                    }
                }
        );

       AppController.getInstance().addToRequestQueue(jsObjRequest);
	}
	private void validate(){
		String code = codeEditText.getText().toString().trim();
		Map<String, String> params = new HashMap<String, String>();
        params.put("code", code);
        params.put("id", (currentUser!=null?(""+currentUser.getId()):"0"));
        params.put("email", currentUser!=null?currentUser.getEmail():"");
		showProgress();
		if(code.equals("")){//TODO Validate email here
			toast(getResources().getString(R.string.error_invalid_activationcode));
			return;
		}
		errorTextView.setText("");
		errorTextView.setVisibility(View.GONE);
		CustomRequest jsObjRequest = new CustomRequest(
				Method.POST, 
				AppConstant.validateUrl, 
				params,
				new Response.Listener<JSONObject>() {
					 
                    @Override
                    public void onResponse(JSONObject response) {
                    	hideProgress();
                    	toast("Response : "+response.toString());
                    	Log.i("Test", response.toString());
                    	parseJsonValidate(response);
                    }
                },
                new Response.ErrorListener() {
 
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    	hideProgress();
                    	toast("Error: " + error.getMessage());
                    	Log.e("Test", error.getMessage());
                    }
                }
        );

       AppController.getInstance().addToRequestQueue(jsObjRequest);
	}
	
	private void showValidatStep(){
		formScrollView.setVisibility(View.GONE);
		codeScrollView.setVisibility(View.VISIBLE);
		registerButton.setText(R.string.activate_account);
		step++;
	}
	
	private void parseJsonRegister(JSONObject response){
		try {
			if(response.has("result_code")){
				String resultCode = response.getString("result_code");
				if(resultCode.equals("success")){
					//String success = response.getString("success");
					//toast(success);
					User user = User.parseFromJsonObject(response);
	            	if(user==null){
	            		errorTextView.setText(getResources().getString(R.string.an_error_occured));
	            		errorTextView.setVisibility(View.VISIBLE);
	            		return;
	            	}
	            	currentUser = user;
					showValidatStep();
				}else if(resultCode.equals("email_used")){
					errorTextView.setText(getResources().getString(R.string.error_email_already_used));
            		errorTextView.setVisibility(View.VISIBLE);
				}else if(response.has("error")){
	            	//String error = response.getString("error");
	            	//toast(error);
	            	errorTextView.setText(getResources().getString(R.string.an_error_occured));
            		errorTextView.setVisibility(View.VISIBLE);
	            }else if(response.has("exception")){
	            	//String error = response.getString("exception");
	            	//toast(error);
	            	errorTextView.setText(getResources().getString(R.string.an_error_occured));
            		errorTextView.setVisibility(View.VISIBLE);
	            }
			}
        } catch (JSONException e) {
            e.printStackTrace();
        }
        hideProgress();
	}
	
	private void parseJsonValidate(JSONObject response){
		try {
			if(response.has("result_code")){
				String resultCode = response.getString("result_code");
				if(resultCode.equals("success")){
					User user = User.parseFromJsonObject(response);
	            	if(user==null){
	            		errorTextView.setText(getResources().getString(R.string.an_error_occured));
	            		errorTextView.setVisibility(View.VISIBLE);
	            		return;
	            	}
					//String success = response.getString("success");
					boolean auth = (response.has("auth"))&&(response.getInt("auth")==1);					
					toast(getResources().getString(R.string.account_activated));
					Intent result = new Intent();
					result.putExtra(EXTRA_USER, user);
					result.putExtra(EXTRA_AUTH, auth);
					setResult(RESULT_OK, result);
					finish(); 
				}else if(resultCode.equals("already_activated")){
					//toast(getResources().getString(R.string.account_already_activated));
					errorTextView.setText(getResources().getString(R.string.account_already_activated));
            		errorTextView.setVisibility(View.VISIBLE);
				}else if(resultCode.equals("not_found")){
					errorTextView.setText(getResources().getString(R.string.error_invalid_activationcode));
            		errorTextView.setVisibility(View.VISIBLE);
					//toast(getResources().getString(R.string.account_not_found));
				}else if(response.has("error")){
	            	//String error = response.getString("error");
	            	//toast(error);
	            	errorTextView.setText(getResources().getString(R.string.an_error_occured));
            		errorTextView.setVisibility(View.VISIBLE);
	            }else if(response.has("exception")){
	            	//String error = response.getString("exception");
	            	//toast(error);
	            	errorTextView.setText(getResources().getString(R.string.an_error_occured));
            		errorTextView.setVisibility(View.VISIBLE);
	            }
			}
        } catch (JSONException e) {
            e.printStackTrace();
        }
        hideProgress();
	}
	
	public void toast(String text){
		Toast.makeText(this, text,Toast.LENGTH_LONG).show();
	}

}
